<?php

namespace App\Http\Controllers\Api;

use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class OAuthController extends Controller
{
    private $http;
    public function __construct(Client $client)
    {
        $this->http = $client;
    }
    public function auth(Request $request)
    {
        //检查用户名和密码是否正确
        if (!Auth::guard()->attempt(['account' => $request->account, 'password' => $request->password])) {
            return response(['message' => '用户名或者密码错误'], 401);
        }
        $response = $this->http->post(env('APP_URL') . '/oauth/token', [
            'form_params' => [
                'grant_type' => 'password',
                'client_id' => env('OAUTH_CLIENT_ID'),
                'client_secret' => env('OAUTH_CLIENT_SECRET'),
                'username' => $request->account,
                'password' => $request->password,
                'scope' => '',
            ],
        ]);
        return json_decode((string) $response->getBody(), true);
    }

    public function user(Request $request)
    {
        $user = $request->user();
        $user->level;
        $user->roles->transform(function($item) {
            return $item->name;
        });
        $user->all_permissions = $user->allPermissions()->transform(function($item) {
            return $item->name;
        });
        return $user;
    }

    public function logout()
    {
        if (Auth::check()) {
            Auth::user()->token()->delete();
        }
        return response(['message' => '退出成功']);
    }
}
